const path = require('path');
const common = require('./webpack.common');
const { merge } = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

// 使用 merge 先合并，然后对合并结果做少量调整（移除生产用的 css 提取插件，替换 css loader）
const config = merge(common, {
    mode: 'development',
    // 更快的 dev source map，适合本地开发
    devtool: 'eval-cheap-module-source-map',
    plugins: [
        new ESLintPlugin({
            // 限定为 src 目录以减少 lint 范围
            context: path.resolve(process.cwd(), 'src'),
            extensions: ['js', 'mjs'],
            cache: true,
            cacheLocation: path.resolve(process.cwd(), 'node_modules/.cache/.eslintcache'),
            lintDirtyModulesOnly: true
        }),
        new HtmlWebpackPlugin({
            inject: false,
            template: path.resolve(process.cwd(), 'src/template.xml'),
            filename: 'Sentry3.xml',
            minify: false
        }),
    ]
});

// 从合并后的配置中移除 MiniCssExtractPlugin（仅在生产构建中需要）
if (config.plugins && Array.isArray(config.plugins)) {
    config.plugins = config.plugins.filter(p => !(p instanceof MiniCssExtractPlugin));
}

// 将 css / less 规则替换为 style-loader 以获得更快的开发构建速度
if (config.module && Array.isArray(config.module.rules)) {
    config.module.rules = config.module.rules.map(rule => {
        try {
            const testStr = rule.test && rule.test.toString();
            if (testStr && testStr.includes('\\.css')) {
                return {
                    test: /\\.css$/,
                    use: ['style-loader', 'css-loader', 'postcss-loader']
                };
            }
            if (testStr && testStr.includes('\\.less')) {
                return {
                    test: /\\.less$/,
                    use: ['style-loader', 'css-loader', 'less-loader', 'postcss-loader']
                };
            }
        } catch (e) {
            // 忽略无法解析的规则
        }
        return rule;
    });
}

module.exports = config;
